package P1线性结构;
//用队列实现栈
public class QueueToStack {
    public static void main(String[] args) {
        StackImplByQueue<Integer> s = new StackImplByQueue<>();
        System.out.println(s);
        s.push(1);
        s.push(2);
        s.push(3);
        System.out.println(s);
        System.out.println(s.pop());
        System.out.println(s);
        System.out.println(s.peek());
        System.out.println(s);
    }
}

class StackImplByQueue<E> implements Stack<E> {
    private ArrayQueue<E> queueA;
    private ArrayQueue<E> queueB;

    public StackImplByQueue() {
        queueA = new ArrayQueue<>();
        queueB = new ArrayQueue<>();
    }

    @Override
    public void push(E element) {
        if (queueA.isEmpty() && queueB.isEmpty()) {
            queueA.offer(element);
        } else if (queueA.isEmpty()) {
            queueB.offer(element);
        } else {
            queueA.offer(element);
        }
    }

    @Override
    public E pop() {
        if (!queueA.isEmpty()) {
            while (queueA.size() > 1) {
                queueB.offer(queueA.poll());
            }
            return queueA.poll();
        } else {
            while (queueB.size() > 1) {
                queueA.offer(queueB.poll());
            }
            return queueB.poll();
        }
    }

    @Override
    public E peek() {
        if (!queueA.isEmpty()) {
            while (queueA.size() > 1) {
                queueB.offer(queueA.poll());
            }
            E ret = queueA.poll();
            queueB.offer(ret);
            return ret;
        } else {
            while (queueB.size() > 1) {
                queueA.offer(queueB.poll());
            }
            E ret = queueB.poll();
            queueA.offer(ret);
            return ret;
        }
    }

    @Override
    public int size() {
        return queueA.size() + queueB.size();
    }

    @Override
    public boolean isEmpty() {
        return queueA.isEmpty() && queueB.isEmpty();
    }

    @Override
    public void clear() {
        queueA.clear();
        queueB.clear();
    }

    @Override
    public String toString() {
        if (!queueA.isEmpty()) {
            return queueA.toString();
        }else {
            return queueB.toString();
        }
    }
}
